package com.goldman.oss.common.internal.processor.context;

import com.goldman.oss.common.platform.FileStorage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.ApplicationContext;
import org.springframework.util.CollectionUtils;

import java.util.List;


@Slf4j
public class ProcessorContextInitializer implements SmartInitializingSingleton {

    @Override
    public void afterSingletonsInstantiated() {
        ApplicationContext applicationContext = OssCommonApplicationContextHolder.getApplicationContext();
        List<?> huaweiObsFileStorages = (List<?>) applicationContext.getBean("huaweiObsFileStorages");
        log.info("huaweiObsFileStorages:{}", huaweiObsFileStorages);
        if (!CollectionUtils.isEmpty(huaweiObsFileStorages)) {
            huaweiObsFileStorages.forEach(e -> {
                ProcessorContext.addFileStorage((FileStorage) e);
            });
        }
        List<?> awsS3FileStorages = (List<?>) applicationContext.getBean("awsS3FileStorages");
        log.info("awsS3FileStorages:{}", awsS3FileStorages);
        if (!CollectionUtils.isEmpty(awsS3FileStorages)) {
            awsS3FileStorages.forEach(e -> {
                ProcessorContext.addFileStorage((FileStorage) e);
            });
        }
    }

    public void destroy() {
        for (FileStorage fileStorage : ProcessorContext.getAllFileStorages()) {
            try {
                fileStorage.close();
            } catch (Exception e) {
                //ignore
            }
        }
    }
}

